<template>
	<view class="patrolReport-container">
		<!-- 自定义头部导航 -->
		<!-- <view class="top-box" :style="{height:totalHeight+'px',paddingTop:customHeight.top+'px'}">
			<view class="content flexWrapNo" :style="{height:customHeight.height+'px'}">
				<uni-icons type="left" size="22" color="#fff" class="back-btn" @tap="goBack"></uni-icons>
				<text class="title">巡店报告</text>
			</view>
		</view> -->

		<view class="main-box">
			<view class="tips">注：合格得满分，不合格得0分</view>
			<view class="list">
				<view class="list-item" v-for="(item,index) in list" :key="index">
					<view class="content">
						{{index+1}}（{{item.score}}分）：{{item.project}}
					</view>
					<view class="choose-box flexWrapNo">
						<view class="choose-item pass" :class="{'active-pass':item.status==0}"
							@tap="handleStatus(index,0)">
							<uni-icons type="checkmarkempty" size="15" color="#fff" v-if="item.status==0"></uni-icons>
							<uni-icons type="checkmarkempty" size="15" color="#999" v-else></uni-icons>
							合格
						</view>
						<view class="choose-item nopass" :class="{'active-nopass':item.status==1}"
							@tap="handleStatus(index,1)">
							<uni-icons type="closeempty" size="15" color="#fff" v-if="item.status==1"></uni-icons>
							<uni-icons type="closeempty" size="15" color="#999" v-else></uni-icons>
							不合格
						</view>
					</view>
					<block v-if="item.status!=null">
						<view class="commit-box" v-if="item.status==0">
							<view class="label">优化建议：</view>
							<textarea v-model="item.suggestion"
								placeholder-style="color:rgba(255,255,255,0.5);font-size:24rpx"
								placeholder="具体优化建议描述" />
						</view>
						<view class="commit-box" v-if="item.status==1">
							<view class="label">问题说明：</view>
							<textarea v-model="item.problem"
								placeholder-style="color:rgba(255,255,255,0.4);font-size:24rpx" placeholder="具体问题描述" />
						</view>
						<view class="commit-box">
							<view class="label">现场问题图片或视频：</view>
							<l-upload :limit="5"
								:files="item&&item.problemAttachment?item.problemAttachment.split(','):[]"
								:series="index" @tap="uploadFile(index)" @complete="complete" @remove="remove">
							</l-upload>
							<view class="tips">图片或视频最多5张</view>
						</view>
						<view class="deadline-box flexWrap" v-if="item.status==1">
							<text class="label">整改截止日期</text>
							<view class="flexWrapNo">
								<picker mode="date" :data-index="index" :value="item.rectificationTime"
									@change="bindDateChange" :start="currentDate">
									<view class="select-input" v-if="item.rectificationTime!=null">
										{{item.rectificationTime.split(' ')[0]}}</view>
									<view class="select-input" v-else>请选择截止日期</view>
								</picker>
								<uni-icons type="right" size="15" color="#fff"></uni-icons>
							</view>
						</view>
					</block>
				</view>
			</view>

			<view class="grade-stat-box flexWrapNo">
				<view class="stat-item">合格项:<text style="color: #2BA471;">{{qualifiedNum}}</text></view>
				<view class="stat-item">不合格项:<text style="color:#D54941;">{{disqualifiedNum}}</text></view>
				<view class="stat-item">星级:<text>{{starScore}}（{{patrolScore}}分）</text></view>
			</view>
			<view class="commit-box">
				<view class="label">巡店总结：</view>
				<textarea v-model="summary" placeholder-style="color:rgba(255,255,255,0.5);font-size:24rpx"
					placeholder="本次巡店整体情况说明" />
			</view>

			<view class="bottom-box flexWrapNo">
				<view class="darft-btn" @tap="saveDraft">保存</view>
				<view class="define-btn" @tap="submit">提交报告</view>
			</view>
		</view>
		<page-container :show="isShow" :overlay="false" @beforeleave="beforeleave" class="page-container">
		</page-container>
	</view>
</template>

<script>
	import utils from '@/common/lib/util.js'
	import lUpload from "@/components/l-upload/l-upload.vue"
	export default {
		components: {
			lUpload
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				customHeight: {
					height: 30,
					top: 20
				},
				statusBarHeight: "",
				navigationBarHeight: "",
				totalHeight: "",
				isShow: true,

				currentDate: currentDate,
				projectList: [],
				list: [],
				currentIndex: '',
				qualifiedNum: 0,
				disqualifiedNum: 0,
				patrolScore: 0,
				starScore: 0,
				deadlineDate: '',
				summary: '',

				type: '',
				draftText: '', // 草稿文本
				flag:0,
			}
		},
		onLoad(options) {
			// #ifdef MP-WEIXIN
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			//胶囊高度
			// 获取微信胶囊的位置信息 width,height,top,right,left,bottom
			this.customHeight = wx.getMenuButtonBoundingClientRect()
			// 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
			this.navigationBarHeight = this.customHeight.height + (this.customHeight.top - this.statusBarHeight) * 2
			// 总体高度 = 状态栏高度 + 导航栏高度
			this.totalHeight = this.navigationBarHeight + this.statusBarHeight
			//#endif

			this.type = options.type
			if (this.type == 'draft') {
				this.getDraft()
			} else {
				this.getProjects()
			}
		},

		watch: {
			list: {
				handler(arr) {
					this.qualifiedNum = 0
					this.disqualifiedNum = 0
					this.patrolScore = 0
					arr.forEach(item => {
						if (item.status == 0) {
							this.qualifiedNum += 1
							this.patrolScore += item.score
						} else if (item.status == 1) {
							this.disqualifiedNum += 1
						}
					})
				},
				deep: true,
			},

			patrolScore: {
				handler(value) {
					let star = this.patrolScore * 5 / 100
					this.starScore = Math.floor(star * 10) / 10
				}
			}
		},
		methods: {
			beforeleave() {
				// this.isShow = false;
				if(this.flag!=1){
					this.goBack();
				}
			},

			// 获取日期 --当前时间
			getDate(type) {
				const date = new Date();
				date.setDate(date.getDate());
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`
			},

			goBack() {
				let obj = {
					patrolType: 2,
					summary: this.summary,
					reportProjectList: this.list,
				}
				let text = JSON.stringify(obj)

				if (!this.checkAllFieldsEmpty(this.list) && this.draftText !== text) {
					uni.showModal({
						title: '提示',
						content: '是否保存?',
						success: (res) => {
							if (res.confirm) {
								this.submitDraft()
								uni.navigateBack({
									delta: this.type == 'draft' ? 1 : 2
								})
							} else {
								uni.navigateBack({
									delta: this.type == 'draft' ? 1 : 2
								})
							}
						},
					})
				} else {
					uni.navigateBack({
						delta: this.type == 'draft' ? 1 : 2
					})
				}
			},

			// 获取所有巡检项
			getProjects() {
				this.$request.get(this.$api.getProjects, {}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
						this.projectList = data
						this.list = []
						this.projectList.forEach(item => {
							this.list.push({
								projectId: item.id,
								score: item.score,
								project: item.project,
								status: null,
								recordType: null,
								suggestion: null,
								problem: null,
								problemAttachment: null,
								rectificationTime: null,
							})
						})
					}
				})
			},

			handleStatus(index, num) {
				this.list[index].status = num
				this.list[index].problem = null
				this.list[index].problemAttachment = null
				this.list[index].rectificationTime = null
				this.list[index].suggestion = null
			},

			uploadFile(index) {
				this.currentIndex = index
			},

			complete(data) {
				this.list[this.currentIndex].problemAttachment = data.fileArr.join(',')
			},
			remove(data) {
				console.log(data)
				this.currentIndex = data.series
				this.list[this.currentIndex].problemAttachment = data.fileArr.join(',')
			},

			// 选择截止日期
			bindDateChange(e) {
				let index = e.target.dataset.index
				this.list[index].rectificationTime = e.detail.value
			},

			// 获取草稿
			getDraft() {
				this.$request.get(this.$api.getDraft, {
					storeId: uni.getStorageSync('store_id'),
				}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
						this.draftText = data.text
						let tempData = JSON.parse(data.text)
						this.summary = tempData.summary
						this.list = tempData.reportProjectList
						this.list.forEach(item => {
							if (item.rectificationTime) {
								item.rectificationTime = item.rectificationTime.split(' ')[0]
							}
						})
					}
				})
			},

			checkAllFieldsEmpty(arr) {
				return arr.every(item => item.status == null);
			},

			submitDraft() {
				let obj = {
					patrolType: 2,
					summary: this.summary,
					reportProjectList: this.list,
				}
				this.$request.post(this.$api.saveDraft, {
					storeId: uni.getStorageSync('store_id'),
					text: JSON.stringify(obj),
				}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
						this.$tools.showToast('保存成功')
						this.getDraft()
					}
				})
			},

			// 存草稿
			saveDraft: utils.debounce(function() {
				// console.log(this.checkAllFieldsEmpty(this.list))
				if (!this.checkAllFieldsEmpty(this.list)) {
					this.submitDraft()
				} else {
					this.$tools.showToast('请至少填写一项检查结果')
				}
			}, 1000),

			// 提交保存
			submit: utils.debounce(function() {
				for (let i = 0; i < this.list.length; i++) {
					if (this.list[i].status == null) {
						this.$tools.showToast('请选择是否合格')
						return
					} else if (this.list[i].status == 0) { //合格
						if (this.list[i].suggestion == null && this.list[i].problemAttachment == null) {
							this.list[i].recordType = 1
						} else {
							this.list[i].recordType = 3
						}
					} else if (this.list[i].status == 1) { //待整改（不合格）
						if (this.list[i].problem == null || this.list[i].problemAttachment == null) {
							this.$tools.showToast('请填写问题说明，并且上传现场图片或视频')
							return
						} else if (this.list[i].rectificationTime == null) {
							this.$tools.showToast('请选择整改截止时间')
							return
						}
						this.list[i].rectificationTime = this.list[i].rectificationTime + " 23:59:59"
						this.list[i].recordType = 2
					}
				}
				if (!this.summary) {
					this.$tools.showToast('请填写巡店总结')
					return
				}

				this.$request.post(this.$api.addReport, {
					storeId: uni.getStorageSync('store_id'),
					patrolType: 2,
					summary: this.summary,
					reportProjectList: this.list,
				}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
						this.$tools.showToast('新增成功')
						this.flag=1
						this.isShow = false
						setTimeout(() => {
							uni.navigateBack({
								delta: this.type == 'draft' ? 1 : 2
							})
						}, 800)
					}
				})
			}, 1000),
		},
	}
</script>

<style lang="scss">
	page {
		position: relative !important;
		top: 0px !important;
	}

	.page-container {
		height: auto;
		/* 设置高度自适应 */
		overflow: auto;
		/* 当内容超出容器范围时显示滚动条 */
	}

	.top-box {
		position: sticky;
		top: 0;
		z-index: 999;
		background: #040336;
		box-sizing: border-box;
		color: #fff;

		.content {
			width: 100%;
			position: relative;

			.back-btn {
				position: absolute;
				left: 20rpx;
			}

			.title {
				width: 100%;
				text-align: center;
				font-size: 28rpx;
			}
		}

	}

	.main-box {
		padding: 28rpx 28rpx 160rpx 28rpx;
		height: 100vh;
		overflow-y: scroll;
	}

	.tips {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.7);
	}

	.list {
		margin-top: 20rpx;

		.list-item {
			margin-bottom: 60rpx;

			.content {
				font-size: 26rpx;
				color: rgba(255, 255, 255, 1);
				line-height: 40rpx;
			}

			.choose-box {
				margin-top: 20rpx;
				gap: 20rpx;
				justify-content: flex-end;

				.choose-item {
					width: 140rpx;
					height: 46rpx;
					line-height: 46rpx;
					border-radius: 46rpx;
					text-align: center;
					font-size: 28rpx;
				}

				.pass {
					color: #999;
					border: 3rpx solid #999;
				}

				.nopass {
					color: #999;
					border: 3rpx solid #999;
				}

				.active-pass {
					color: #fff;
					border: 3rpx solid rgb(102, 203, 53);
					background: rgb(102, 203, 53);
				}

				.active-nopass {
					color: #fff;
					border: 3rpx solid rgb(189, 49, 36);
					background: rgb(189, 49, 36);
				}
			}
		}
	}

	.commit-box {
		margin-top: 20rpx;

		.label {
			color: #fff;
			font-size: 28rpx;
			margin-bottom: 14rpx;
		}

		textarea {
			width: 100%;
			height: 200rpx;
			background: rgba(53, 52, 132, 0.5);
			border-radius: 16rpx;
			padding: 20rpx;
			box-sizing: border-box;
			color: #fff;
			font-size: 28rpx;
		}

		.tips {
			margin-top: 14rpx;
			color: rgba(255, 255, 255, 0.5);
			font-size: 24rpx;
		}
	}

	.deadline-box {
		margin-top: 20rpx;
		border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
		padding-bottom: 20rpx;

		.label {
			color: rgba(255, 255, 255, 1);
			font-size: 28rpx;
		}

		.select-input {
			color: rgba(255, 255, 255, 1);
			font-size: 28rpx;
		}
	}

	.grade-stat-box {
		margin-top: 20rpx;
		gap: 30rpx;

		.stat-item {
			color: #fff;
			font-size: 28rpx;

			text {
				margin-left: 8rpx;
				font-weight: bold;
			}
		}
	}

	.bottom-box {
		width: 100%;
		padding-top: 14rpx;
		padding-bottom: 62rpx;
		background: #040336;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		justify-content: center;
		gap: 30rpx;
		z-index: 11;

		.darft-btn {
			font-size: 32rpx;
			font-weight: 500;
			color: #26BCFD;
			width: 200rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			border: 1rpx solid #26BCFD;
			box-sizing: border-box;
			text-align: center;
		}

		.define-btn {
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			width: 450rpx;
			height: 80rpx;
			line-height: 80rpx;
			background: #26BCFD;
			border-radius: 40rpx;
			text-align: center;
		}
	}
</style>